package de.graph.document.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import de.graph.document.Document;
import de.graph.document.DocumentManager;

public class DocumentManagerImpl implements DocumentManager {

    private static final DocumentManager instance = new DocumentManagerImpl();

    private final Map<Long, Document> documentMap;

    private DocumentManagerImpl() {
        this.documentMap = Collections.synchronizedMap(new LinkedHashMap<Long, Document>());
    }

    public static final DocumentManager getInstance() {
        return instance;
    }

    public void addDocument(Document document) {
        if (document == null) {
            return;
        }

        documentMap.put(document.getId(), document);
    }

    public void removeDocument(Document document) {
        if (document == null) {
            return;
        }

        documentMap.remove(document.getId());
    }

    public Document getDocument(DocumentKey key) {
        return documentMap.get(key.getId());
    }

    public Collection<Document> getDocuments() {
        return documentMap.values();
    }

    public void clear() {
        documentMap.clear();
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        builder.append("Documents:\n");
        for (Document document : getDocuments()) {
            builder.append("document (");
            builder.append(document.getId());
            builder.append(")\n");
            for (String key : document.getPropertyKeys()) {
                Object object = document.getProperty(key);

                builder.append("  ");
                builder.append(key);
                builder.append("=");
                builder.append(object);
                builder.append("\n");
            }
        }

        return builder.toString();
    }
}
